package com.qf.service.impl;

import com.qf.entity.ReserveCar;
import com.qf.entity.Task;
import com.qf.entity.User;
import com.qf.enums.OAExceptionEnum;
import com.qf.exception.OAException;
import com.qf.mapper.ReserveCarMapper;
import com.qf.mapper.TaskMapper;
import com.qf.service.ReserveCarService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ReserveCarServiceImpl implements ReserveCarService {

    @Resource
    private ReserveCarMapper reserveCarMapper;
    @Resource
    private TaskMapper taskMapper;

    @Override
    public Integer findByInfo(ReserveCar reserveCar) {
        Integer count=reserveCarMapper.findByInfo(reserveCar);
        return count;
    }

    @Override
    public void save(ReserveCar reserveCar) {
        List<User> userList =reserveCarMapper.findUserIdByRoleId(2);
        List<ReserveCar> reserveCar1 =reserveCarMapper.findInfoReserveCar(reserveCar.getCarId());
        if(reserveCar1.size()>0){

            for (ReserveCar car : reserveCar1) {
                if(reserveCar.getStartTime().after(reserveCar.getEndTime())){
                    log.error("【预定车辆信息】预定车辆失败，reserveCar={}",reserveCar);
                    throw new OAException(11,"开始时间不能小于结束时间");
                }
                if(!(reserveCar.getStartTime().after(car.getEndTime())||
                        reserveCar.getEndTime().before(car.getStartTime()))){
                    log.error("【预定车辆信息】预定车辆失败，reserveCar={}",reserveCar);
                    throw new OAException(OAExceptionEnum.RESERVECAR_TIME_ERROR);
                }
            }
        }
        for (User user : userList) {
            reserveCar.setTaskId(3);
            reserveCar.setAuditStatus(0);
            reserveCar.setAuditTime(new Date());
            reserveCar.setUserId(user.getUserId());
            Integer count= reserveCarMapper.addReserveCar(reserveCar);
            if(count!=1){
                log.error("【添加预定车辆信息】添加预订车辆信息失败】reserveCar={}",reserveCar);
                throw new OAException(OAExceptionEnum.RESERVECAR_ADD_ERROR);
            }
            Task param = new Task();
            param.setApplyName(reserveCar.getRealName());
            param.setApplyTime(reserveCar.getAuditTime());
            param.setTaskId(reserveCar.getTaskId());
            param.setStatus(reserveCar.getAuditStatus());
            param.setUserId(reserveCar.getUserId());
            param.setEventId(reserveCar.getReserveId());
            int num = taskMapper.insert(param);
        }

    }
}
